<?php
/**
 * @author GhostWei
 * @date Sep 10, 2012
 */
class oauth_open_iweibo extends oauth_api_abstract {
	
	protected $_name = 'iweibo';
	protected $_url = array(
			'authorize' => 'https://open.t.qq.com/cgi-bin/oauth2/authorize',
			'token' => 'https://open.t.qq.com/cgi-bin/oauth2/access_token',
			'user_info' => 'https://open.t.qq.com/api/user/info'
	);
	/**
	 * @return oauth_api_response
	 */
	public function request($action = null, $params = array()) {
		$response = $this->getOauthResponse();
		if(empty($params)) {
			$oauth = $this->getSession()->getToken();
			if(!(isset($oauth['access_token']) && isset($oauth['app_id']) && isset($oauth['app_key']))) {
				return $response->addError('access token is empty or invalid');
			}	
			$params = array(
					'format' => 'json',
					'oauth_version' => '2.a',
					'access_token' => $oauth['access_token'], 
					'oauth_consumer_key' => $this->getSource()->getAppId(),
					'openid' => $oauth['app_id'],
					'clientip' => system_controller_front::getInstance()->getRequest()->getClientIp(true),
					'scope' => 'all'
			);
		}
		if($action === null) {
			$url = $this->_url['user_info'];
		} elseif(is_string($action)) {
			$url = $action;
		} else {
			return $response->addError('invalid request');
		}
		$symbol = strpos($url, '?') ? '&' : '?';
		if(!($body = $this->get($url . $symbol . http_build_query($params)))) {
			return $response->addError('HTTP RESPONSE IS NOT OK');
		}
		if(1 && $data = $this->parseJson($body)) {
			return $response->setData($data);
		} else {
			return $response;
		}
	}
	
	/**
	 * @return oauth_open_iweibo
	 */
	public function authorize() {
		$request = $this->getRequest();
		$code = $request->getQuery('code');
		$open_id = $request->getQuery('openid');
		$open_key = $request->getQuery('openkey');
		
		if(!$code || !$open_id || !$open_key) {
			$this->addError('code, open id or open key is empty');
			return $this;
		}
		
		$p = array();
		$p['client_id'] = $this->getSource()->getAppId();
		$p['client_secret'] = $this->getSource()->getAppKey();
		$p['grant_type'] = 'authorization_code';
		$p['code'] = $code;
		$p['redirect_uri'] = $this->getRedirectUrl(false);
		if(!($response = $this->get($this->_url['token'] . '?' . http_build_query($p)))) {
			$this->addError('HTTP RESPONSE IS NOT OK');
			return $this;
		}
		parse_str($response, $token);
		if(isset($token['errorCode']) && isset($token['errorMsg'])) {
			return $this->addError($token['errorMsg'], $token['errorCode']);
		}
		if(!(isset($token['access_token']) && isset($token['expires_in']))) {
			return $this->addError('access token params error');
		}

		$this->getSession()->setToken(array(
				'access_token' => $token["access_token"],
				'app_id' => $open_id,
				'app_key' => $open_key,
				'expires' => $token["expires_in"]
		));
		return $this;
	}
	
	/**
	 * @param unknown_type $g_ut 仅WAP网站接入时使用。QQ登录页面版本（1：wml版本； 2：xhtml版本），默认值为1
	 */
	public function url($g_ut = null) {
		$p = array();
		$p['client_id'] = $this->getSource()->getAppId();
		$p['response_type'] = 'code';
		$p['redirect_uri'] = $this->getRedirectUrl(false);
		if($g_ut !== null) {
			if(intval($g_ut) == 1) {
				$p['wap'] = 1;
			} else {
				$p['wap'] = 2;
			}
		}
		return $this->_url['authorize'] . '?' . http_build_query($p);
	}
	
	private function parseJson($response) {
		$json = trim($response);
		try {
			$data = json_decode($json);
			if(isset($data->errcode) && $data->errcode != 0 && isset($data->msg) && $data->msg != 'ok') {
				$this->addError($data->msg, $data->errcode);
				return null;
			}
			return isset($data->data) ? $data->data : null;
		} catch (Exception $e) {
			$this->addError($e->getMessage());
		}
		return null;
	}
	
}
